package com.thinkcoder.aspect;

import com.thinkcoder.service.DefaultApiAuthenticateImpl;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author : 商俊帅
 * @Date : 2021/4/5 17:26
 * @Description :
 */
@Aspect
@Order(1)
@Component
public class AuthAspect {

    @Resource
    private DefaultApiAuthenticateImpl apiAuthenticate;

    @Around("@annotation(AuthAnnotation)")
    public Object authenticate(ProceedingJoinPoint joinPoint) throws Throwable {

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        //http://localhost:8086/test
        String requestUrl = request.getRequestURL().toString();
        //id=4&appKey=order&timeStamp=123123&nonce=423123
        String queryString = request.getQueryString();
        //http://localhost:8086/test?id=4&appKey=order&timeStamp=123123&nonce=423123
        String requestUrlWithParams = requestUrl.concat("?").concat(queryString);

        boolean auth = apiAuthenticate.auth(requestUrlWithParams);
        if (!auth){
            return false;
        }
        //执行控制器中的方法
        joinPoint.proceed();
        return null;
    }
}
